package com.aidex.biz.utils.hengchang;

import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.asn1.pkcs.RSAPrivateKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class ClientRSAUtil {
    private static final Logger log = LoggerFactory.getLogger(ClientRSAUtil.class);
    public static final String KEY_ALGORITHM = "RSA";
    /**
     * 第二步：用公钥 pubKeyString 加密数据 dataStr
     * @param pubKey
     * @throws Exception
     */
    public static String rsaEncryptByPubKey(String pubKey, String data ) throws Exception {
        log.info("ClientRSAUtil##rsaEncryptByPubKey：公钥是：【{}】，待加密内容是：【{}】",pubKey, data);
        /**
         * 公钥加密
         */
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key publick = keyFactory.generatePublic(new X509EncodedKeySpec(Base64Util.decryptBASE(pubKey)));
        // 对数据加密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, publick);
        byte[] result =  cipher.doFinal(data.getBytes());
        String requestBase = Base64Util.encryptBASE(result);
        log.info("ClientRSAUtil##rsaEncryptByPubKey：公钥加密后的数据是：【{}】", requestBase);
        return requestBase;
    }

    /**
     * 用私钥解密
     * @param privateKey
     * @param data
     * @return
     * @throws Exception
     */
    public static String rsaDecryptByPriKey(String privateKey, String data ) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key privatek = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(Base64Util.decryptBASE(privateKey)));
        // 对数据加密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, privatek);
        byte[] decodedBytes = Base64Util.decryptBASE(data);
        byte[] decryptedBytes = cipher.doFinal(decodedBytes);
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }
    /**
     * 生成 RSA 密钥对
     * @return 生成的 RSA 密钥对
     * @throws NoSuchAlgorithmException 如果不支持 RSA 算法
     */
    public static KeyPair generateRSAKeyPair() throws NoSuchAlgorithmException {
        // 获取 RSA 密钥对生成器
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        // 初始化密钥对生成器，密钥长度为 2048 位
        keyPairGenerator.initialize(1024);
        // 生成密钥对
        return keyPairGenerator.generateKeyPair();
    }

    /**
     * 将密钥编码为 Base64 字符串
     * @param key 要编码的密钥
     * @return 编码后的 Base64 字符串
     */
    public static String encodeKeyToBase64(Key key) {
        byte[] keyBytes = key.getEncoded();
        return Base64.getEncoder().encodeToString(keyBytes);
    }
    public static KeyPair generateKeyPair(int keySize) throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(keySize);
        return keyPairGenerator.generateKeyPair();
    }


    public static void main(String[] args) {
        try {
            KeyPair keyPair = generateKeyPair(1024);

            // 获取公钥和私钥
            PublicKey publicKey = keyPair.getPublic();
            PrivateKey privateKey = keyPair.getPrivate();

            // 将公钥和私钥转换为 Base64 编码的字符串
            String publicKeyBase64 = Base64.getEncoder().encodeToString(publicKey.getEncoded());
            String privateKeyBase64 = Base64.getEncoder().encodeToString(privateKey.getEncoded());

            // 打印公钥和私钥
            System.out.println("公钥 (Base64): " + publicKeyBase64);
            System.out.println("私钥 (Base64): " + privateKeyBase64);

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

}
